package co.yixiang.modules.shop.web.controller;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.aop.log.Log;
import co.yixiang.exception.ErrorRequestException;
import co.yixiang.modules.order.service.YxStoreOrderCartInfoService;
import co.yixiang.modules.order.service.YxStoreOrderStatusService;
import co.yixiang.modules.order.web.dto.*;
import co.yixiang.modules.order.web.param.InvestOrderParam;
import co.yixiang.modules.shop.entity.YxInvestCustomer;
import co.yixiang.modules.shop.entity.YxInvestOrder;
import co.yixiang.modules.shop.entity.YxSales;
import co.yixiang.modules.shop.entity.YxStoreProduct;
import co.yixiang.modules.shop.service.*;
import co.yixiang.modules.shop.web.param.YxInvestOrderQueryParam;
import co.yixiang.modules.shop.web.vo.YxInvestCartQueryVo;
import co.yixiang.modules.shop.web.vo.YxInvestOrderQueryVo;
import co.yixiang.common.web.controller.BaseController;
import co.yixiang.common.api.ApiResult;
import co.yixiang.modules.shop.web.vo.YxSalesManageQueryVo;
import co.yixiang.modules.shop.web.vo.YxStoreCartQueryVo;
import co.yixiang.service.KryConfigService;
import co.yixiang.service.dto.ScanCodePay;
import co.yixiang.service.impl.KryConfigServiceImpl;
import co.yixiang.utils.SecurityUtils;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import co.yixiang.common.web.vo.Paging;
import co.yixiang.common.web.param.IdParam;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.alibaba.fastjson.JSON;

/**
 * <p>
 * 认购订单表 前端控制器
 * </p>
 *
 * @author hisen
 * @since 2020-06-10
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "订单模块", tags = "投资端:订单模块", description = "订单模块")
public class YxInvestOrderController extends BaseController {
    private final YxInvestOrderService yxInvestOrderService;
    private final YxInvestCartService yxInvestCartService;
    private final YxSystemConfigService systemConfigService;
    private final YxStoreProductService storeProductService;
    private final YxSalesService yxSalesService;
    private final YxInvestCustomerService yxInvestCustomerService;
    private final YxSalesManageService yxSalesManageService;
    private final KryConfigServiceImpl kryConfigService;





    private static Lock lock = new ReentrantLock(false);


    /**
     * 订单确认
     */
    @PostMapping("/order/confirm")
    @ApiOperation(value = "订单确认",notes = "订单确认")
    public ApiResult<ConfirmInvestOrderDTO> confirm(@RequestBody String jsonStr){
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String cartId = jsonObject.getString("cartId");
        if(StrUtil.isEmpty(cartId)){
            return ApiResult.fail("请提交购买的商品");
        }
        int uid = SecurityUtils.getUserId().intValue();
        Map<String, Object> cartGroup = yxInvestCartService.getUserProductCartList(uid,cartId,1);
        if(ObjectUtil.isNotEmpty(cartGroup.get("invalid"))){
            return ApiResult.fail("有失效的商品请重新提交");
        }
        if(ObjectUtil.isEmpty(cartGroup.get("valid"))){
            return ApiResult.fail("请提交购买的商品");
        }
        List<YxInvestCartQueryVo> cartInfo = (List<YxInvestCartQueryVo>)cartGroup.get("valid");
        BigDecimal price = BigDecimal.ZERO;
        for (YxInvestCartQueryVo storeCart : cartInfo) {
            //查询保留商品
            YxStoreProduct product = storeProductService.getById(storeCart.getProductId());
            if(product.getLockStatus()!= null && product.getLockStatus() == 1 && product.getLockerId() != uid){
                return ApiResult.fail("商品："+product.getStoreName()+"正在被认购中");
            }


        }

        for (YxInvestCartQueryVo storeCart : cartInfo) {
            price = NumberUtil.add(price,
                    NumberUtil.mul(storeCart.getCartNum(),storeCart.getInvestPrice()));

        }
        ConfirmInvestOrderDTO confirmOrderDTO = new ConfirmInvestOrderDTO();
        confirmOrderDTO.setCartInfo(cartInfo);
        confirmOrderDTO.setOrderKey(yxInvestOrderService.cacheOrderInfo(uid,cartInfo,
                price.doubleValue()));

        return ApiResult.ok(confirmOrderDTO);
    }

    /**
     * 订单创建
     */
    @PostMapping("/order/create/{key}")
    @ApiOperation(value = "订单创建",notes = "订单创建")
    public ApiResult<ConfirmInvestOrderDTO> create(@RequestBody @Valid InvestOrderParam param,
                                                   @PathVariable String key){

        Map<String,Object> map = new LinkedHashMap<>();
        int uid = SecurityUtils.getUserId().intValue();
        if(StrUtil.isEmpty(key)) return ApiResult.fail("参数错误");
        YxInvestOrderQueryVo storeOrder = yxInvestOrderService.getOrderInfo(key,uid);
        if(ObjectUtil.isNotNull(storeOrder)){
            map.put("status","EXTEND_ORDER");
            OrderExtendDTO orderExtendDTO = new OrderExtendDTO();
            orderExtendDTO.setKey(key);
            orderExtendDTO.setOrderId(storeOrder.getOrderId());
            map.put("result",orderExtendDTO);
            return ApiResult.ok(map,"订单已生成");
        }


        //创建订单
        YxInvestOrder order = null;
        try{
            lock.lock();
            order = yxInvestOrderService.createOrder(uid,key,param);
        }finally {
            lock.unlock();
        }


        if(ObjectUtil.isNull(order)) throw new ErrorRequestException("订单生成失败");

        String orderId = order.getOrderId();

        OrderExtendDTO orderDTO = new OrderExtendDTO();
        orderDTO.setKey(key);
        orderDTO.setPrice(order.getPrice());
        orderDTO.setOrderId(orderId);
        //生成支付码
        if(param.getPayType().equals("2")){
            ScanCodePay ScanCodePay = new ScanCodePay();
            ScanCodePay.setOutTradeNo(key);
            ScanCodePay.setPayOrg(param.getPayOrg());
      //  ScanCodePay.setPayOrg("ORG_ALIPAY");
         //   ScanCodePay.setPayFee(order.getPrice().longValue() *  100);
           ScanCodePay.setPayFee(1L);
          ScanCodePay.setProductDesc("订单支付");

            Map<String, Object> kryResult = kryConfigService.scanCode(ScanCodePay);
            if(kryResult.get("resultParams") !=null){
                JSONObject object =   JSONObject.parseObject((String)kryResult.get("resultParams"));
                //成功
                if(object.getString("code").equals("0")){
                    JSONObject resultObject = object.getJSONObject("result");
                    orderDTO.setPayUrl(resultObject.getString("codeUrl"));

                }
                else{
                    return ApiResult.fail("系统异常");
                }
            }

        }
        log.info("支付码url:"+orderDTO.getPayUrl());
        map.put("status","SUCCESS");
        map.put("result",orderDTO);


        return ApiResult.ok(map,"订单创建成功");
    }

//
//
//
    /**
     * 订单列表
     */

    @Log(value = "查看订单列表(个人)",type = 1)
    @GetMapping("/order/list")
    @ApiOperation(value = "订单列表(个人)",notes = "订单列表(个人)")
    public ApiResult<List<YxInvestOrderQueryVo>> orderList(YxInvestOrderQueryParam queryParam){
        int uid = SecurityUtils.getUserId().intValue();
        return ApiResult.ok(yxInvestOrderService.orderList(uid,null,queryParam.getType(),
                queryParam.getPage().intValue(),queryParam.getLimit().intValue()));
    }

    /**
     * 订单列表
     */
    @Log(value = "查看订单列表(团队)",type = 1)
    @GetMapping("/teamOrder/list")
    @ApiOperation(value = "订单列表(团队)",notes = "订单列表(团队)")
    public ApiResult<List<YxInvestOrderQueryVo>> teamOrderList(YxInvestOrderQueryParam queryParam){
        List<Integer>  saleIdList = null;
        int uid = SecurityUtils.getUserId().intValue();
            YxSales yxSales = yxSalesService.getById(uid);
             List<YxSalesManageQueryVo> saleList = yxSalesManageService.getListByManagerId(yxSales.getUid());
         if(yxSales.getGroupId() == 2){
            //如果是经理，查询他负责的业务员
            saleList = yxSalesManageService.getListByManagerId(yxSales.getUid());
            if(saleList != null && saleList.size() > 0){
                saleIdList = new ArrayList<>();
                for(YxSalesManageQueryVo yxSalesManageQueryVo : saleList){
                    saleIdList.add(yxSalesManageQueryVo.getUid());
                }
            }
        }

        if(queryParam.getSalesId() != -1){
            uid = queryParam.getSalesId();
        }


        return ApiResult.ok(yxInvestOrderService.orderListTeam(uid,null,queryParam.getType(),
                queryParam.getPage().intValue(),queryParam.getLimit().intValue(),saleIdList));
    }
//
//
    /**
     * 订单详情
     */
    @Log(value = "查看订单详情",type = 1)
    @GetMapping("/order/detail/{key}")
    @ApiOperation(value = "订单详情",notes = "订单详情")
    public ApiResult<YxInvestOrderQueryVo> detail(@PathVariable String key){
        int uid = SecurityUtils.getUserId().intValue();
        if(StrUtil.isEmpty(key)) return ApiResult.fail("参数错误");
         YxSales yxSales = yxSalesService.getById(uid);
         if(yxSales.getGroupId() == 4){
             uid = 0;
         }
        YxInvestOrderQueryVo storeOrder = yxInvestOrderService.getOrderInfo(key,uid);
        if(ObjectUtil.isNull(storeOrder)){
            return ApiResult.fail("订单不存在");
        }
         return ApiResult.ok(yxInvestOrderService.handleOrder(storeOrder));

     }

    /**
     * 订单详情
     */
    @Log(value = "查询订单支付状态",type = 1)
    @GetMapping("/order/paid/{key}")
    @ApiOperation(value = "查询订单支付状态",notes = "查询订单支付状态")
    public ApiResult<String> orderPaid(@PathVariable String key){
        int uid = SecurityUtils.getUserId().intValue();
        if(StrUtil.isEmpty(key)) return ApiResult.fail("参数错误");
        YxInvestOrderQueryVo storeOrder = yxInvestOrderService.getOrderInfo(key,uid);
        if(ObjectUtil.isNull(storeOrder)){
            return ApiResult.fail("订单不存在");
        }
        return ApiResult.ok(storeOrder.getPaid());

    }

    /**
     * 查询二维码支付状态
     */
    @Log(value = "查询二维码支付状态",type = 1)
    @GetMapping("/order/codeUrl/{key}")
    @ApiOperation(value = "查询二维码支付状态",notes = "查询二维码支付状态")
    public ApiResult<String> orderCodeUrl(@PathVariable String key){
        int uid = SecurityUtils.getUserId().intValue();
        if(StrUtil.isEmpty(key)) return ApiResult.fail("参数错误");
        YxInvestOrder storeOrder = yxInvestOrderService.getOrderInfo(key);
        if(ObjectUtil.isNull(storeOrder)){
            return ApiResult.fail("订单不存在");
        }
        if(storeOrder.getPaid()  ==  1){
            return ApiResult.ok(1);
        }
        //
          Map<String, Object> kryResult = kryConfigService.payQuery(storeOrder.getOrderTradeNo());
         String payStatus = "";
         if(kryResult.get("resultParams") !=null){
            JSONObject object =   JSONObject.parseObject((String)kryResult.get("resultParams"));
            //成功
            if(object.getString("code").equals("0")){
                JSONObject resultObject = object.getJSONObject("result");
                payStatus =   resultObject.getString("payStatus");
            }

        }
        if(payStatus.equals("PAYSUCCESS")){
            //更新二维码支付状态
              storeOrder.setPaid(1);
            storeOrder.setInvestStatus(2);
            yxInvestOrderService.updateById(storeOrder);
                    return ApiResult.ok(1);
        }
        else{
            return ApiResult.ok(0);

        }

    }

    /**
     * 生成在线支付二维码
     */
    @Log(value = "生成在线支付二维码",type = 1)
    @GetMapping("/order/kryPaid")
    @ApiOperation(value = "生成在线支付二维码",notes = "生成在线支付二维码")
    public ApiResult<String> orderKryPaid(@RequestParam String key, @RequestParam String payOrg){
        int uid = SecurityUtils.getUserId().intValue();
        if(StrUtil.isEmpty(key)) return ApiResult.fail("参数错误");
        YxInvestOrder storeOrder = yxInvestOrderService.getOrderInfo(key);
        if(ObjectUtil.isNull(storeOrder)){
            return ApiResult.fail("订单不存在");
        }
        if(storeOrder.getPaid()  ==  1){
            return ApiResult.fail("订单已支付");
        }


        String payUrl = "";
        if(storeOrder.getPayType().equals("2")){
            String orderTradeNo =  IdUtil.simpleUUID();
            ScanCodePay ScanCodePay = new ScanCodePay();
            ScanCodePay.setOutTradeNo(orderTradeNo);
             ScanCodePay.setPayOrg(storeOrder.getPayOrg());
             ScanCodePay.setPayFee(1L);
            ScanCodePay.setProductDesc("订单支付");
            Map<String, Object> kryResult = kryConfigService.scanCode(ScanCodePay);
            if(kryResult.get("resultParams") !=null){
                JSONObject object =   JSONObject.parseObject((String)kryResult.get("resultParams"));
                //成功
                if(object.getString("code").equals("0")){
                    JSONObject resultObject = object.getJSONObject("result");
                    payUrl = resultObject.getString("codeUrl");
                }
                else{
                    return ApiResult.fail("系统异常");
                }
            }
            log.info("payUrl:"+payUrl);
            //更新支付单号
            storeOrder.setOrderTradeNo(orderTradeNo);
            storeOrder.setPayOrg(payOrg);
            yxInvestOrderService.updateById(storeOrder);

        }

        return ApiResult.ok(payUrl);

    }
//
//    /**
//     * 计算订单金额
//     */
//    @PostMapping("/order/computed/{key}")
//    @ApiOperation(value = "计算订单金额",notes = "计算订单金额")
//    public ApiResult<Map<String,Object>> computedOrder(@RequestBody String jsonStr,
//                                                       @PathVariable String key){
//
//        Map<String,Object> map = new LinkedHashMap<>();
//        int uid = SecurityUtils.getUserId().intValue();
//        if(StrUtil.isEmpty(key)) return ApiResult.fail("参数错误");
//        YxStoreOrderQueryVo storeOrder = storeOrderService.getOrderInfo(key,uid);
//        if(ObjectUtil.isNotNull(storeOrder)){
//            map.put("status","EXTEND_ORDER");
//            OrderExtendDTO orderExtendDTO = new OrderExtendDTO();
//            orderExtendDTO.setKey(key);
//            orderExtendDTO.setOrderId(storeOrder.getOrderId());
//            map.put("result",orderExtendDTO);
//            return ApiResult.ok(map,"订单已生成");
//        }
//
//        JSONObject jsonObject = JSON.parseObject(jsonStr);
//        String addressId = jsonObject.getString("addressId");
//        String couponId = jsonObject.getString("couponId");
//        String shippingType = jsonObject.getString("shipping_type");
//        String useIntegral = jsonObject.getString("useIntegral");
//
//
//        ComputeDTO computeDTO = storeOrderService.computedOrder(uid,key,
//                Integer.valueOf(couponId),
//                Integer.valueOf(useIntegral),
//                Integer.valueOf(shippingType));
//
//
//        map.put("result",computeDTO);
//        map.put("status","NONE");
//        return ApiResult.ok(map);
//    }
//
//
//
//
//    /**
//     * 订单产品信息
//     */
//    @PostMapping("/order/product")
//    @ApiOperation(value = "订单产品信息",notes = "订单产品信息")
//    public ApiResult<Object> product(@RequestBody String jsonStr){
//        JSONObject jsonObject = JSON.parseObject(jsonStr);
//        String unique = jsonObject.getString("unique");
//        if(StrUtil.isEmpty(unique)) return ApiResult.fail("参数错误");
//
//        YxStoreOrderCartInfo orderCartInfo = orderCartInfoService.findByUni(unique);
//
//        YxStoreCartQueryVo cartInfo = JSONObject.parseObject(orderCartInfo.getCartInfo(),
//                YxStoreCartQueryVo.class);
//
//
//        OrderCartInfoDTO orderCartInfoDTO = new OrderCartInfoDTO();
//        orderCartInfoDTO.setBargainId(cartInfo.getBargainId());
//        orderCartInfoDTO.setCartNum(cartInfo.getCartNum());
//        orderCartInfoDTO.setCombinationId(cartInfo.getCombinationId());
//        orderCartInfoDTO.setOrderId(storeOrderService
//                .getById(orderCartInfo.getOid()).getOrderId());
//        orderCartInfoDTO.setSeckillId(cartInfo.getSeckillId());
//
//        ProductDTO productDTO = new ProductDTO();
//        productDTO.setImage(cartInfo.getProductInfo().getImage());
//        productDTO.setPrice(cartInfo.getProductInfo().getPrice().doubleValue());
//        productDTO.setStoreName(cartInfo.getProductInfo().getStoreName());
//        if(ObjectUtil.isNotEmpty(cartInfo.getProductInfo().getAttrInfo())){
//            ProductAttrDTO productAttrDTO = new ProductAttrDTO();
//            productAttrDTO.setImage(cartInfo.getProductInfo().getAttrInfo().getImage());
//            productAttrDTO.setPrice(cartInfo.getProductInfo().getAttrInfo().getPrice().doubleValue());
//            productAttrDTO.setProductId(cartInfo.getProductInfo().getAttrInfo().getProductId());
//            productAttrDTO.setSuk(cartInfo.getProductInfo().getAttrInfo().getSuk());
//            productDTO.setAttrInfo(productAttrDTO);
//        }
//
//        orderCartInfoDTO.setProductInfo(productDTO);
//
//
//        return ApiResult.ok(orderCartInfoDTO);
//
//    }





}

